const username = document.querySelector('input#username');
const inputRoom = document.querySelector('input#room');
const connectBtn = document.querySelector('button#connect');
const outputArea = document.querySelector('textarea#output');
const inputArea = document.querySelector('textarea#input');
const sendBtn = document.querySelector('button#send');
const leaveBtn = document.querySelector('button#leave');

let socket,
  room;

connectBtn.onclick = () => {
  //connect
  socket = io();

  //recieve message
  socket.on('joined', (roomId, socketId) => {
    connectBtn.disabled = true;
    leaveBtn.disabled = false;
    inputArea.disabled = false;
    sendBtn.disabled = false;


  });
  socket.on('leaved', (roomId) => {
    connectBtn.disabled = false;
    leaveBtn.disabled = true;
    inputArea.disabled = true;
    sendBtn.disabled = true;


  });
  socket.on('message', (room, socketId, data) => {
    console.log('收到了');
    outputArea.value = outputArea.value + data + '\r';
  });

  socket.on('disconnect', (socket)=>{
    connectBtn.disabled = false;
    leaveBtn.disabled = true;
    inputArea.disabled = true;
    sendBtn.disabled = true;
  });

  //send message
  room = inputRoom.value
  socket.emit('join', room);
};

sendBtn.onclick = () => {
  let data = inputArea.value;
  data = username.value + ':' + data;
  socket.emit('message', room, data);
  inputArea.value = '';
};

leaveBtn.onclick = ()=>{
  room = inputRoom.value;
  socket.emit('leave', room);
}

inputArea.onkeypress = (event)=> {
  //event = event || window.event;
  if (event.keyCode === 13) { //回车发送消息
    let data = inputArea.value;
    data = username.value + ':' + data;
    socket.emit('message', room, data);
    inputArea.value = '';
    event.preventDefault();//阻止默认行为
  }
}
